package com.activenetwork.smlite.page.generic;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.activenetwork.smlite.page.HeaderPage;
import com.activenetwork.smlite.page.LoginErrorPage;
import com.activenetwork.smlite.page.LoginPage;
import com.activenetwork.smlite.page.NavigateBar;
import com.activenetwork.smlite.page.rfp.ViewRFPDetailTemplate;
import com.activenetwork.smlite.page.rfp.RfpMaintenanceView.RfpReview;
import com.activenetwork.util.EnvContext;
import com.activenetwork.util.WaitUtil;

public class NexusProgressPageObjectListener implements PageObjectListener {
	private Logger logger = LoggerFactory.getLogger(NexusProgressPageObjectListener.class);
	private By progressBy = By.xpath("//div[@id='nexus-progress']");
	private List<Class<? extends PageObject>> exceptions = new ArrayList<Class<? extends PageObject>>();
	
	public NexusProgressPageObjectListener(){
		exceptions.add(HeaderPage.class);
		exceptions.add(LoginPage.class);
		exceptions.add(LoginErrorPage.class);
		exceptions.add(NavigateBar.class);
		exceptions.add(ViewRFPDetailTemplate.class);
		exceptions.add(RfpReview.class);
	}
	
	@Override
	public void addException(Class<? extends PageObject> pageObjectClazz){
		exceptions.add(pageObjectClazz);
		logger.debug(pageObjectClazz.getSimpleName() + " is added in NexusProgressPageObjectListener exceptions");
	}
	
	@Override
	public void removeException(Class<? extends PageObject> pageObjectClazz){
		if(exceptions.contains(pageObjectClazz)){
			exceptions.remove(pageObjectClazz);
			logger.debug(pageObjectClazz.getSimpleName() + " is removed from NexusProgressPageObjectListener exceptions");
		}else{
			throw new RuntimeException("No such page class in exception of NexusProgressPageObjectListener : " + pageObjectClazz.getSimpleName());
		}
	}

	@Override
	public void afterLoad(PageObject pageObject) {
		//check exception
		if(exceptions.contains(pageObject.getClass())){
			return;
		}
		String pageName = pageObject.getClass().getName();
		waitProgress(pageName);		
	}
	
	public void waitProgress(String page){
		// Get each thread webdriver instance
		WebDriver driver = EnvContext.webDriverTL.get();
		WaitUtil waitUtil = new WaitUtil();
		
		try{
			logger.debug(page + " has progress bar");
			while(true){
				WebElement div = driver.findElement(progressBy);
				String attr = div.getAttribute("class");
				if(StringUtils.contains(attr, "hide")){
					break;
				}else{
					waitUtil.wait(500);
				}
			}
		}catch(NoSuchElementException e){
			logger.debug("Unable to find the nexus progress on this page " + page);
		}
		
	}

}
